//路由相关全局通用方法和数据
import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/system/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'

const state={
  //页面路由信息
  routes: [],
    //添加的路由
    addRoutes: [],
    //默认路由
    defaultRoutes: [],
    //顶部导航栏路由
    topbarRouters: [],
    //侧边栏路由
    sidebarRouters: []
}

//mutations是Vuex中唯一允许更新应用状态的函数，是同步函数
const mutations = {
  /**
   * 添加路由
   * @param state
   * @param routes
   * @constructor
   */
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  /**
   * 添加默认路由
   * @param state
   * @param routes
   * @constructor
   */
  SET_DEFAULT_ROUTES: (state, routes) => {
    state.defaultRoutes = constantRoutes.concat(routes)
  },
  /**
   * 设置顶部导航栏路由
   * @param state
   * @param routes
   * @constructor
   */
  SET_TOPBAR_ROUTES: (state, routes) => {
    state.topbarRouters = routes
  },
  /**
   * 设置侧边栏路由
   * @param state
   * @param routes
   * @constructor
   */
  SET_SIDEBAR_ROUTERS: (state, routes) => {
    state.sidebarRouters = routes
  },
}

//actions是Vuex中处理异步操作的函数，它们不能直接修改状态，而是通过调用 mutations 来间接修改状态
const actions = {
  /**
   * 从后端获取并动态生成路由
   * @param commit
   * @returns {Promise<unknown>}
   * @constructor
   */
  GenerateRoutes({ commit }) {
    return new Promise(resolve => {
      // 向后端请求路由数据
      getRouters().then(res => {
        const sdata = JSON.parse(JSON.stringify(res.data))
        const rdata = JSON.parse(JSON.stringify(res.data))
        const sidebarRoutes = filterAsyncRouter(sdata)
        const rewriteRoutes = filterAsyncRouter(rdata, false, true)
        const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
        rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(asyncRoutes);
        commit('SET_ROUTES', rewriteRoutes)
        commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
        commit('SET_DEFAULT_ROUTES', sidebarRoutes)
        commit('SET_TOPBAR_ROUTES', sidebarRoutes)
        resolve(rewriteRoutes)
      })
    })
  }
}

/**
 * 遍历后端传来的路由字符串，转换为组件对象
 * @param asyncRouterMap
 * @param lastRouter
 * @param type
 * @returns {*}
 */
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        //普通嵌入系统页面布局的子菜单视图
        route.component = Layout
      } else if (route.component === 'ParentView') {
        //外部链接
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        //内部链接
        route.component = InnerLink
      } else {
        //指定页面路径
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

/**
 * 遍历子组件路由字符串，转换为组件对象
 * @param childrenMap
 * @param lastRouter
 * @returns {*[]}
 */
function filterChildren(childrenMap, lastRouter = false) {
  let children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

/**
 * 动态路由遍历，验证是否具备权限
 * @param routes
 * @returns {*[]}
 */
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

/**
 * 加载路由
 * @param view
 * @returns {(function(*): *)|(function(): Promise<*>)}
 */
export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    //return () => import(`@/views/${view}`)
    return (resolve) => require([`@/views/${view}`], resolve)
  }
}

export default {
  // 必须加模块名前缀
  namespaced: true,
  state,
  mutations,
  actions
}
